<template>
  <div class="product-template-info-record">
    <div class="product-template-timeline" ref="timeline">
      <base-timeline 
        :data="recordPage.list" 
        :record-render="renderRecord" 
        :loading="recordLoading"
        :loadmore="recordPage.hasNextPage"
        @load="loadmore"/>
    </div>
      
    <div class="product-template-quick-comment" v-if="editComment">
      <!-- <base-comment ref="comment" placeholder="请输入备注内容" @submit="createRemark" :disabled="commentPending" autofocus/> -->
      <biz-comment ref="comment" :placeholder="$t('product.placeholder.remark')" @submit="createRemark" :disabled="commentPending" autofocus user-search-url="/message/user/lists" :search-params="{seeAllOrg:true}"></biz-comment>
    </div>

  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import { trimAll, cutAtTextContent } from 'pub-bbx-utils';
import Page from '@model/Page';
import platform from '@src/platform';
import { useTenantId } from '@hooks/useRootWindow.ts';

import { getProductTemplateRecord, productTemplateCreateRecord, productTemplateDeleteRecord } from '@src/api/ProductApi.js';

function createAttachmentDom(h, attachments){
  return attachments && attachments.length > 0 
    ? <div class="base-timeline-attachment base-file__preview">
      {attachments.map(item => <base-file-item Source={attachments} file={item} key={item.id} readonly size="small"/>)}
    </div> 
    : ''
}
function createLinkDom(h, s){
  const reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=\+\$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\?\+=&;:%!\/@.\w_]*)#?(?:[-\+=&;%!\?\/@.\w_]*))?)/g;
  const str = s.replace(reg, str=>`@#@${str}@#@`);
  const arr = str.split('@#@');
  return <p class="pre-line secondary-info">{arr.map(item=>{
    if(item.indexOf('http') === 0){
      return <a href={item} target='_blank'>{item}</a>
    }
    return <biz-comment-html html={item}></biz-comment-html>
    
  })}</p>
}
import { translateAction } from '@src/util/record'
export default {
  name: 'product-template-info-record',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      commentPending: false,
      params: {
        primaryId: this.shareData.productTemplate.id,
        pageNum: 1,
        pageSize: 15,
      },
      recordLoading: false, // loading 状态
      recordPage: new Page(), // 页面数据
    }
  },
  inject: ['initData'],
  computed: {
    // 权限
    authorities(){
      let user = this.loginUser || {};
      return user.authorities || {};
    },
    /** 是否允许操作 */
    allowOperate(){
      return this.productTemplate.isDelete === 0;
    },
    /** 编辑权限 */
    allowEditProduct() {
      return this.shareData.allowEditProduct;
    },
    /** 添加备注权限 */
    editComment(){
      return (this.allowEditProduct && this.allowOperate);
    },
    // 当前用户id
    loginUser(){
      return this.shareData.loginUser;
    },
    // 产品模板数据
    productTemplate() {
      return this.shareData.productTemplate || {}
    }
  },
  mounted() {
    this.initRecord();
    this.$eventBus.$on('customer_info_record.update_record_list', this.searchRecord);
  },
  destroyed() {
  },
  methods: {
    /** 
     * 同时满足以下条件允许删除该记录
     * 1. 该记录没有被删除
     * 2. 产品编辑权限（PRODUCT_EDIT）值为3 或者 是创建人
     * 3. 该客户没有被删除
     */
    allowDeleteRecord(item){
      let isDelete = item.content && item.content.isDelete == 'true';
      let authorities = this.authorities;
      let user = this.loginUser;
      let isCreator = item.userId == user.userId;

      return !isDelete && ((authorities['PRODUCT_EDIT'] && authorities['PRODUCT_EDIT'] == 3) || isCreator) && this.allowOperate;
    },
    /** 添加备注 */
    async createRemark(form){
      try{
        this.commentPending = true;
        let tenantId = useTenantId().value;
        let url = ''
        let productTemplate = this.productTemplate
        if(form.receivers){
          url = `?tenantId=${tenantId}&bizId=${productTemplate.id}&sendUserName=${this.initData.loginUser.displayName}&receivers=${form.receivers}&templateId=${productTemplate.templateId || ''}&templateName=${productTemplate.templateName || ''}&bizNo=${productTemplate.name}`
          url += `&content=${cutAtTextContent(form.originalContent)}`
        }
        let params = {
          primaryId: this.productTemplate.id,
          primaryName: this.productTemplate.name,
          attachments: form.attachments,
          showInOwn: form.showInOwn,
          content: {
            updateContent: form.content,
            updateType: 'ptRecord'
          }
        }
        params.url = url
        let result = await productTemplateCreateRecord(params);
        const isSucc = (result.status == 0);

        this.$platform.notification({
          title: isSucc ? this.$t('product.productTemplate.tips.tip14') : this.$t('product.productTemplate.tips.tip15'),
          message: !isSucc && result.message,
          type: isSucc ? 'success' : 'error',
        });

        if(isSucc){
          this.$refs.comment.reset();
          this.initRecord();

          this.$nextTick(() => {
            this.$refs.timeline.scrollTop = 0;
          })

        }

        this.commentPending = false;
      }catch(e){
        console.error(e)
      }
    },
    /** 删除备注 */
    async deleteRemark(record) {
      try {
        if (!await platform.confirm(this.$t('product.productTemplate.tips.tip18'))) return;

        const result = await productTemplateDeleteRecord({id: record.id});
        const isSucc = (result.status == 0)

        this.$platform.notification({
          title: isSucc ? this.$t('product.productTemplate.tips.tip16') : this.$t('product.productTemplate.tips.tip17'),
          message: !isSucc && result.message,
          type: isSucc ? 'success' : 'error',
        });

        if(isSucc) this.initRecord();

      } catch (e) {
        console.error('product template deleteRemark  err', e);
      }
    },
    /** 抓取信息动态 */
    fetchRecord(params){
      return getProductTemplateRecord(params);
    },
    // 初始化信息动态
    initRecord() {
      this.params.pageNum = 1;
      this.searchRecord();
    },
    // 加载更多
    async loadmore() {
      try {
        this.params.pageNum++;
        this.params['primaryId'] = this.shareData?.productTemplateId || '';
        this.recordLoading = true;

        let result = await this.fetchRecord(this.params);

        this.recordLoading = false;
        this.recordPage.merge(result);
      } catch (error) {
        console.error(`product template record loadmore err ${error}`)
      }
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item){
      let {action, userName, showInOwn, content, attachments, primaryName, staffId, userId} = item;
      
      if(action == '备注'){
        return [
          <h5 class="main-info">
            {this.renderUserName(userName, staffId, userId)}{this.$t('common.record.addRemark')}
            {!!showInOwn && (
              <span class="private">
                <i class="iconfont icon-account1"></i>{this.$t('common.record.onlyVisibleToYourself')}
              </span>
            )}。
            {
              this.allowDeleteRecord(item) 
              && <el-button class="btn-text base-timeline-delete" onClick={e => this.deleteRemark(item)}>
                <i class="iconfont icon-shanchu"></i>{this.$t('common.base.delete')}
              </el-button>
            }
          </h5>,
          content.isDelete == 'true'
            ? <p class="text-danger">{this.$t('common.record.sbDeleteRemark', {name: content.deleteUserName, time: content.deleteTime})}</p> 
            : [createLinkDom(h, content.updateContent), createAttachmentDom(h, attachments)]
        ]
      }

      return [
        <h5>{this.renderUserName(userName, staffId, userId)} {this.$t('common.record.product.productTemplate.record1', {action:translateAction(action)})}</h5>,
        content.updateFields ? <p class="secondary-info">{this.$t('product.modifyField')}：{content.updateFields}</p> : '',
        createAttachmentDom(h, attachments)
      ];
    },
    renderUserName(userName, staffId, userId){
      return (
        <recordUserName userName={userName} staffId={staffId} userId={userId} />
      )
    },
    // 查询信息动态
    async searchRecord() {
      try {
        this.recordLoading = true;
        this.params['primaryId'] = this.shareData?.productTemplateId || '';
        let result = await this.fetchRecord(this.params);

        this.recordLoading = false;
        this.recordPage.list = [];
        this.recordPage.merge(result);

        this.$emit('changeRecordCount', result.total);
        
      } catch (error) {
        console.error(`searchRecord ${error}`)
      }
    }
  }
}
</script>

<style lang="scss">
.product-template-info-record {
  height: 100%;

  display: flex;
  flex-flow: column nowrap;

  h5 {
    margin-bottom: 5px;
    .icon-address {
      margin-left: 5px;
    }
  }

  .private {
    @include fontColor();
    .iconfont {
      font-size: 14px;
      margin: 0 6px;
    }
  }

  .secondary-info {
    margin-top: 8px;
  }
}

.product-template-timeline{
  padding-top: 15px;
  padding-right: 15px;

  flex: 1;
  overflow: auto;
}

.product-template-quick-comment{
  position: sticky;
  bottom: 0;
  z-index: 1;

  padding: 0px;

  background-color: #fff;
  box-shadow: 0 -1px 2px rgba(0,0,0, .095);

  .base-comment{
    border-color: transparent;
  }
}
</style>